package com.kuangjia.scenic_spot_ticket.controller;

import com.kuangjia.scenic_spot_ticket.common.Result;
import com.kuangjia.scenic_spot_ticket.dto.UserInfoDTO;
import com.kuangjia.scenic_spot_ticket.entity.User;
import com.kuangjia.scenic_spot_ticket.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping
    public Result<List<UserInfoDTO>> list() {
        List<UserInfoDTO> users = userService.list().stream().map(u ->
            new UserInfoDTO(u.getId(), u.getUsername(), u.getRole(), u.getBalance())
        ).collect(Collectors.toList());
        return Result.success(users);
    }

    @PostMapping
    public Result<Boolean> add(@RequestBody User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return Result.success(userService.save(user));
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody User user) {
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(null);
        }
        return Result.success(userService.updateById(user));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(userService.removeById(id));
    }

    @GetMapping("/page")
    public Result<Page<UserInfoDTO>> page(@RequestParam(defaultValue = "1") int page,
                                          @RequestParam(defaultValue = "10") int size,
                                          @RequestParam(required = false) String keyword) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(User::getUsername, keyword);
        }
        Page<User> userPage = userService.page(new Page<>(page, size), wrapper);
        
        // 手动转换Page<User>为Page<UserInfoDTO>
        Page<UserInfoDTO> dtoPage = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserInfoDTO> dtoList = userPage.getRecords().stream()
            .map(u -> new UserInfoDTO(u.getId(), u.getUsername(), u.getRole(), u.getBalance()))
            .collect(Collectors.toList());
        dtoPage.setRecords(dtoList);
        
        return Result.success(dtoPage);
    }

    @GetMapping("/me")
    public Result<UserInfoDTO> getCurrentUser(@RequestParam String username) {
        User user = userService.lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            return Result.error("用户不存在");
        }
        UserInfoDTO dto = new UserInfoDTO(user.getId(), user.getUsername(), user.getRole(), user.getBalance());
        return Result.success(dto);
    }
} 